class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int left = 0, right = matrix[0].size(), top = 0,
            bottom = matrix.size(); // 确定四个边界，边界往外一个方便计算
        vector<int> ans;
        while (left < right && top < bottom) {
            for (int i = left; i < right; i++) {
                ans.push_back(matrix[top][i]);
            }
            top++;
            if (top == bottom) {
                break;
            }

            for (int i = top; i < bottom; i++) {
                ans.push_back(matrix[i][right - 1]);
            }
            right--;
            if (right == left)
                break;
            for (int i = right - 1; i >= left; i--) {
                ans.push_back(matrix[bottom - 1][i]);
            }
            bottom--;
            if (bottom == top) {
                break;
            }

            for (int i = bottom - 1; i >= top; i--) {
                ans.push_back(matrix[i][left]);
            }
            left++;
            if (left == right)
                break;
        }

        return ans;
    }
};<Paste>
